# -*- coding:utf-8 -*-
# @Time     :2024/3/14 22:26
# @Author   :CHNJX
# @File     :performance_result_processor.py
# @Desc     :分析性能结果
from openpyxl import load_workbook
from datetime import datetime, timedelta
import os


class PerformanceResultProcessor:
    def __init__(self, performance_data_path):
        self.performance_data_path = performance_data_path

    def process_performance_results(self):
        """分析性能数据，并汇总问题"""
        if not os.path.exists(self.performance_data_path):
            print("Performance data file does not exist.")
            return {}

        performance_issues = {}
        workbook = load_workbook(self.performance_data_path)
        yesterday_str = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")

        for sheet_name in workbook.sheetnames:
            if yesterday_str in sheet_name:
                sheet = workbook[sheet_name]
                performance_issues[sheet_name.split('_')[0]] = self.analyze_sheet(sheet)

        return performance_issues

    def analyze_sheet(self, sheet):
        """分析单个工作表的性能数据"""
        yesterday_md_str = (datetime.now() - timedelta(days=1)).strftime("%m%d")
        cpu_issues = []
        mem_issues = []

        for row in sheet.iter_rows(min_row=2, values_only=True):
            timestamp, cpu, mem = row
            if cpu and cpu > 90:
                cpu_issues.append(f"{yesterday_md_str}-{timestamp.strip()}-{cpu}%")
            if mem and mem > 95:
                mem_issues.append(f"{yesterday_md_str}-{timestamp.strip()}-{mem}%")
        for index, issue in enumerate(cpu_issues):
            cpu_issues[index] = f'{index + 1}. {issue}'
        for index, issue in enumerate(mem_issues):
            mem_issues[index] = f'{index + 1}. {issue}'
        return {
            'cpu监控': ('fail' if cpu_issues else 'pass', '\n '.join(cpu_issues)),
            '内存监控': ('fail' if mem_issues else 'pass', '\n '.join(mem_issues))
        }
